package cn.fxyz.web.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import cn.fxyz.entity.Dinnertable;
import cn.fxyz.entity.Food;
import cn.fxyz.entity.Foodtype;
import cn.fxyz.page.PageBean;
import cn.fxyz.service.DinnertableService;
import cn.fxyz.service.FoodService;
import cn.fxyz.service.FoodtypeService;
@Controller
@RequestMapping("/food")
public class FoodController {
	@Resource
	private FoodService foodService;
	@Resource
	private DinnertableService dinnertableService;
	@Resource
	private FoodtypeService foodtypeService;

	public FoodService getFoodService() {
		return foodService;
	}
	public void setFoodService(FoodService foodService) {
		this.foodService = foodService;
	}
	//分页查询
	private int pageSize = 4;  //固定值
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	@RequestMapping("pageFindAll")
	@ResponseBody
	public List<Food> pageFindAll(PageBean<Food> pagebean,Food food,@RequestParam("typeid") Integer typeid) {
		PageBean<Food> p = foodService.findAll(food, pagebean.getPageNum(), pageSize,typeid);
		List<Food> list=(ArrayList<Food>)p.getData();
		return list;
	}
	/*@RequestMapping("pageFindAll")
	public List<Food> pageFindAll(PageBean<Food> pagebean,Food food,@RequestParam("typeid") Integer typeid) {
		PageBean<Food> p = foodService.findAll(food, pagebean.getPageNum(), pageSize,typeid);
		List<Food> list=(ArrayList<Food>)p.getData();
		return list;
	}*/

	//通过id查询食物
	@RequestMapping("findById")
	public String findById(Food food,Model model) {
		Food findFood = foodService.findById(food);
		model.addAttribute("findFood", findFood);
		return "reception/detail/caixiangxi";
	}
	//添加购物车
	@RequestMapping("addShoppingCar")
	public String addShoppingCar(Food food,Model model,HttpServletRequest request) {
		Food findFood = foodService.findById(food);
		System.out.println(findFood);
		HttpSession session = request.getSession();
		if(session.getAttribute("findFoods") == null) {
			List<Food> findFoods = new ArrayList<Food>();
			findFoods.add(findFood);
			session.setAttribute("findFoods", findFoods);
		} else {
			List<Food> list = (List<Food>) session.getAttribute("findFoods");
			for (Food f : list) {
				if(f.getId() == findFood.getId()) {
					f.setNum(f.getNum()+1);
					session.setAttribute("findFoods", list);
					return "reception/detail/clientCart";
				}
			}
			list.add(findFood);
			session.setAttribute("findFoods", list);
		}
		List<Dinnertable> dinnertables = dinnertableService.findByTableStatus();
		model.addAttribute("dinnertables", dinnertables);
		return "reception/detail/clientCart";
	}
	
	//购物车登录跳转
	@RequestMapping("cartLogin")
	public String cartLogin(Model model) {
		List<Dinnertable> dinnertables = dinnertableService.findByTableStatus();
		model.addAttribute("dinnertables", dinnertables);
		return "reception/detail/clientCart";
	}
	
	//异步修改session中的数量
	@RequestMapping("mudifyNum")
	public @ResponseBody String mudifyNum(Food food,HttpServletRequest request,
			HttpServletResponse response) {
		Food findFood = foodService.findById(food);
		HttpSession session = request.getSession();
		List<Food> list = (List<Food>) session.getAttribute("findFoods");
		Float price = null;
		for (int i = 0;i < list.size();i++) {
			Food f = list.get(i);
			if(f.getId() == findFood.getId()) {
				f.setNum(food.getNum());
				session.setAttribute("findFoods", list);
				price = findFood.getPrice() * f.getNum();
			}
		
		}
		return price.toString();
	}
	
	//删除购物车的菜单项
	@RequestMapping("removeFoodCart")
	public @ResponseBody String removeFoodCart(Integer id,HttpServletRequest request) {
		HttpSession session = request.getSession();
		List<Food> list = (List<Food>) session.getAttribute("findFoods");
		int listSize = list.size();
		for (int i = 0;i < listSize;i++) {
			Food f = list.get(i);
			if(f.getId() == id) {
				list.remove(f);
				break;
			}
		}
		return "success";
	}
	
	//下面后台红能
	
	@RequestMapping(value="/food/getuser",method=RequestMethod.GET)
	public String getFood(String id,String foodname,String foodtype,Model model){
		try{
			List<Food> list=new ArrayList<Food>();
			list=foodService.getFood(id, foodname, foodtype);
			model.addAttribute("lists",list);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "backstage/detail/foodList";
	}
	

	//添加菜品（包含图片上传）
	//@RequestMapping(value="/upload",method=RequestMethod.POST)
	@RequestMapping(value="addFood",method=RequestMethod.POST)
	public String addFood(Food foods,@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request)throws Exception{
		 //基本表单
		//获取物理路径webapp所在路径
		 String pathRoot=request.getSession().getServletContext().getRealPath("/upload");
		 String path="";
		 if(!file.isEmpty()){
			 //生成UUID作为文件名称
			 String uuid=UUID.randomUUID().toString().replaceAll("-","");
			 //获取文件类型（可以判断如果不是图片，禁止上传）
			 String contentType=file.getContentType();
			 //获得文件后缀名称
			 String imageName=contentType.substring(contentType.indexOf("/")+1);
			 File dir = new File(pathRoot);
			 if(!dir.exists()) {
				 dir.mkdirs();
			 }
			 path=uuid+"."+imageName;
			 file.transferTo(new File(pathRoot,path));
		 }	
		 request.setAttribute("imagePath", path);
		 foods.setImg(path);
		 foodService.addFood(foods);
		 return "redirect:getAll.do";
/*		System.out.println(123);
		MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
		System.out.println(request.getParameter("price"));*/
	}
	
	//添加菜品
	@RequestMapping("toAddFood")
	public String toAddFood(Model model){
		List<Foodtype> foodtype = foodtypeService.findAll();
		model.addAttribute("foodtype", foodtype);
		return "/backstage/detail/saveFood";
	}
	
	 @RequestMapping("getAll")
	 public String getAll(HttpServletRequest request){
		 List<Food> foods=foodService.findAll();
		 request.setAttribute("foods", foods);
		 return "/backstage/detail/foodList";
	 }
	
	 
	 //删除菜式
	@RequestMapping("/deleteFood")
	public @ResponseBody String deleteFood(String id,HttpServletResponse response){
		String result="error";
		if(foodService.deleteFood(id)){
			result="success";
		}
		/*response.setContentType("application/json");
		try{
			PrintWriter out=response.getWriter();
			out.write(result);
		}catch(IOException e){
			e.printStackTrace();
		}*/
		return result;
	}
	
	@RequestMapping("/getFood")
	public String getFood(String id,HttpServletRequest request){
		Food food=foodService.getFood(id);
		request.setAttribute("food", food);
		return "/editFood";
	}
	
	//修改菜式,上传
	@RequestMapping(value="modifyFood",method=RequestMethod.POST)
	public String modifyFood(Food foods,@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request)throws Exception{
		 //基本表单
		//获取物理路径webapp所在路径
		 String pathRoot=request.getSession().getServletContext().getRealPath("/upload");
		 String path="";
		 System.out.println(foods);
		 System.out.println(file);
		 if(!file.isEmpty()){
			 //生成UUID作为文件名称
			 String uuid=UUID.randomUUID().toString().replaceAll("-","");
			 //获取文件类型（可以判断如果不是图片，禁止上传）
			 String contentType=file.getContentType();
			 //获得文件后缀名称
			 String imageName=contentType.substring(contentType.indexOf("/")+1);
			 File dir = new File(pathRoot);
			 if(!dir.exists()) {
				 dir.mkdirs();
			 }
			 path=uuid+"."+imageName;
			 file.transferTo(new File(pathRoot,path));
		 }	
		 request.setAttribute("imagePath", path);
		 foods.setImg(path);
		 foodService.modifyFood(foods);
		 return "redirect:getAll.do";
/*		System.out.println(123);
		MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
		System.out.println(request.getParameter("price"));*/
	}
	/*//图片名字
	public String getNewFileName(CommonsMultipartFile file) {
		String newFileName="";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		newFileName = sdf.format(new Date());
		//获取文件扩展名
		String originalFilename = file.getOriginalFilename();
		String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
		newFileName += suffix;
		return newFileName;
	}*/
	//通过id查询菜品，用于菜品更新回显
	@RequestMapping("findFoodById")
	public String findFoodById(Food food,Model model) {
		Food findFood = foodService.findById(food);
		List<Foodtype> foodtype = foodtypeService.findAll();
		model.addAttribute("foodtype", foodtype);
		model.addAttribute("findFood", findFood);
		return "backstage/detail/updateFood";
	}
	
}
